import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import type User from './User.model';

class AuditLog extends Model {
  public id!: string;
  public tenantId!: string | null;
  public userId!: string;
  public action!: string;
  public resource!: string;
  public resourceId?: string;
  public changes?: any;
  public ipAddress?: string;
  public userAgent?: string;
  public readonly createdAt!: Date;

  // 关联属性
  public user?: User;
}

AuditLog.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    userId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'user_id',
    },
    action: {
      type: DataTypes.ENUM(
        'create',
        'update',
        'delete',
        'login',
        'logout',
        'activate',
        'deactivate',
        'suspend',
        'restore'
      ),
      allowNull: false,
    },
    resource: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    resourceId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'resource_id',
    },
    changes: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    ipAddress: {
      type: DataTypes.STRING(45),
      allowNull: true,
      field: 'ip_address',
    },
    userAgent: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'user_agent',
    },
  },
  {
    sequelize,
    tableName: 'audit_logs',
    underscored: true,
    timestamps: true,
    updatedAt: false,
  },
);

export default AuditLog;

